#include "student.h"
#include "course.h"
#include <time.h>

// 添加学生信息
void add_student(Student **head, const char *id, const char *name, const Course *course_head, const CourseIDArray course_ids, int num_courses, int is_file)
{
    Student *new_student = (Student *)malloc(sizeof(Student));
    if (new_student == NULL)
    {
        perror("Failed to allocate memory for new student");
        return;
    }
    // 添加学生的基本信息
    strcpy(new_student->id, id);
    strcpy(new_student->name, name);
    new_student->courses = NULL;
    new_student->total_credits = 0;
    new_student->next = *head;
    *head = new_student;

    // 遍历课程ID集合，查找并添加课程信息
    for (int i = 0; i < num_courses; ++i)
    {
        Course *new_course = (Course *)malloc(sizeof(Course));
        if (new_course == NULL)
        {
            perror("Failed to allocate memory for new course");
            continue;
        }

        strcpy(new_course->id, course_ids[i]);
        new_course->credits = 3;
        strcpy(new_course->properties, "选修");
        new_course->selected_num = 5;
        new_course->max_students = 100;
        new_course->next = new_student->courses;
        new_student->courses = new_course;
        new_student->total_credits += new_course->credits;
    }
    if (is_file == 0)
    {
        printf("添加学生信息成功！\n");
    }

    //记录添加学生日志
    log_action("Add-student", id);
}

// 打印学生的所选课程列表
void print_student_courses(const Student *student)
{
    const Course *course = student->courses;
    printf("所选课程id列表：");
    while (course != NULL)
    {
        printf("%s ", course->id);
        course = course->next;
    }
    printf("\n");
}

// 删除学生信息
void delete_student(Student **head, const char *id)
{
    Student *current = *head, *prev = NULL;
    while (current != NULL && strcmp(current->id, id) != 0)
    {
        prev = current;
        current = current->next;
    }
    if (current == NULL)
    {
        printf("学生ID为： %s 的学生没有发现.\n", id);
        return;
    }
    if (prev == NULL)
    {
        *head = current->next;
    }
    else
    {
        prev->next = current->next;
    }
    free(current);

    printf("删除学生信息成功！\n");
    //记录删除学生日志
    log_action("Delete", id);
}

// 更新学生信息
void update_student(Student **head, const char *id)
{
    Student *student = get_student(head, id);
    if (student == NULL)
    {
        printf("学生ID为： %s 的学生没有发现.\n", id);
        return;
    }
    char item;
    printf("是否要更新姓名？ (y / n)\n");
    scanf(" %c", &item);
    if (item == 'y')
    {
        printf("请输入的新姓名: ");
        scanf("%s", student->name);
    }
    printf("是否要更新选课列表？ (y / n)\n");
    scanf(" %c", &item);
    if (item == 'y')
    {
        print_student_courses(student);
    }
    printf("更新成功!\n");

    //记录更新学生日志
    log_action("Update", id);
}

// 查询学生信息
void find_student(const Student *head, const char *id)
{
    const Student *student = get_const_student(head, id);
    if (student == NULL)
    {
        printf("学生ID为： %s 的学生没有发现.\n", id);
        return;
    }
    printf("ID: %s, 姓名: %s, 总学分: %d\n", student->id, student->name, student->total_credits);
    // 打印课程列表
    print_student_courses(student);

    //记录查询学生日志
    log_action("find", id);
}

// 列出所有学生信息
void list_students(const Student *head)
{
    const Student *current = head;
    while (current != NULL)
    {
        printf("ID: %s, 姓名: %s, 总学分: %d\n", current->id, current->name, current->total_credits);

        // 打印课程列表
        print_student_courses(current);
        current = current->next;
    }
}

// 判断学生是否存在
int contains_student(const Student *head, const char *id)
{
    const Student *current = head;
    while (current != NULL)
    {
        if (strcmp(current->id, id) == 0)
        {
            return 1;
        }
        current = current->next;
    }
    return 0;
}
// 返回学生指针
Student *get_student(Student **head, const char *id)
{
    Student *current = *head;
    while (current != NULL)
    {
        if (strcmp(current->id, id) == 0)
        {
            return current;
        }
        current = current->next;
    }
    return NULL;
}

const Student *get_const_student(const Student *head, const char *id)
{
    const Student *current = head;
    while (current != NULL)
    {
        if (strcmp(current->id, id) == 0)
        {
            return current;
        }
        current = current->next;
    }
    return NULL;
}
// 从文件中加载学生信息（包含所选的课程列表信息）
void load_students_from_file(Student **head, const char *filename, const Course *course_head)
{
    FILE *file = fopen(filename, "r");
    if (file == NULL)
    {
        perror("Failed to open file");
        return;
    }

    char id[20], name[50];
    CourseIDArray course_ids; // 课程ID集合
    int num_courses = 0;

    while (fscanf(file, "%s %s", id, name) == 2)
    {
        // 读取课程ID直到遇到 "end" 标记
        num_courses = 0;
        for (int i = 0; i < 20; ++i)
        {
            course_ids[i] = (char *)malloc(20 * sizeof(char)); // 分配内存
            if (course_ids[i] == NULL)
            {
                perror("为课程id分配内存失败");
                exit(EXIT_FAILURE);
            }
        }
        while (fscanf(file, "%s", course_ids[num_courses]) == 1)
        {
            if (strcmp(course_ids[num_courses], "end") == 0)
            {
                break; // 遇到 "end" 标记，表示当前学生课程信息结束
            }
            num_courses++;
        }

        // 添加学生基本信息及课程信息
        add_student(head, id, name, course_head, course_ids, num_courses, 1);

        fgetc(file);
    }

    fclose(file);

    // 释放 course_ids 数组中的内存
    for (int i = 0; i < 20; ++i)
    {
        free(course_ids[i]);
    }
}

// 将添加的学生信息保存到文件
void save_students_to_file(const Student *head, const char *filename)
{
    FILE *file = fopen(filename, "w");
    if (file == NULL)
    {
        perror("Failed to open file");
        return;
    }

    const Student *current = head;

    while (current != NULL)
    {
        fprintf(file, "%s %s\n", current->id, current->name);
        // 添加学生的选课列表

        const Course *current_course = current->courses;
        const Course *p = current_course;
        int count = 0;
        // 通过遍历学生的课程列表获取课程数目
        while (p != NULL)
        {
            count++;
            p = p->next;
        }
        current_course = current->courses; // 重新初始化 current_course
        for (int i = 0; i < count; i++)
        {
            fprintf(file, "%s\n", current_course->id);
            current_course = current_course->next;
        }
        fprintf(file, "end\n");

        current = current->next;
    }

    fclose(file);
}

// 记录日志
void log_action(const char *action, const char *details)
{
    FILE *log_file = fopen("../log/log.log", "a");
    if (log_file == NULL)
    {
        perror("Failed to open log file");
        return;
    }

    // 使用time()系统调用获取当前时间
    time_t now = time(NULL);
    char *time_str = ctime(&now);
    time_str[strlen(time_str) - 1] = '\0';

    fprintf(log_file, "[%s] %s: %s\n", time_str, action, details);
    fclose(log_file);
}
